import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/bean/call_Record_list_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/tonghuajilu/RightEndDrawer.dart';
import 'package:jyofservice/util/CallRecordNotification.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class CallRecordPage extends StatefulWidget {
  @override
  _CallRecordPageState createState() => _CallRecordPageState();
}

class _CallRecordPageState extends State<CallRecordPage> {

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  List<CallRecordListData> callRecordData = [];
  ScrollController scrollController = ScrollController();
  int page = 1;
  String? wherestr = "1=1";
  bool isloading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getCallRecordData();
    scrollController.addListener((){

      if(scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {

        print('滑动到了最底部');
        page++;

        getCallRecordData();
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<CallRecordNotification>(

      onNotification: (notification) {
        isloading = false;
        if (mounted) {
          setState(() {
            callRecordData.clear();
            page = 1;
            wherestr = notification.wherestr;
            getCallRecordData();
          });
        }
        return true;
      },
      child: Scaffold(

        key: _scaffoldKey,
        appBar: AppBar(
          elevation: 0.5,
          centerTitle: true,
          leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () {
                Navigator.pop(context, false);
              }),
          title: Text('通话记录',
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(45))),

        ),

        body: Container(
          color: const Color(0xFFF2F5F9),
          child:Stack(
            alignment: Alignment(0.5, 0.5),
            children: <Widget>[
              RefreshIndicator(child: ListView(

                //下拉刷新也会调用  scrollController.addListener(() 方法
                physics: AlwaysScrollableScrollPhysics(),
                controller: scrollController,
                children: <Widget>[

                  SingleChildScrollView(

                    scrollDirection: Axis.horizontal,
                    child: DataTable(
//                Datacollen (label: Container (child: Text ('2011') ，color: Colors.grey,)
                        columns:[

                          DataColumn(

                              label: Text(

                                '工单号',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '电话号码',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '呼叫类型',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '内线号码',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '客服人员',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '呼叫时间',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '接通时间',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '挂断时间',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '连线情况',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),
                          DataColumn(

                              label: Text(
                                '挂断方式',
                                style: TextStyle(fontSize: ScreenUtil().setSp(40),fontWeight: FontWeight.bold,color: Colors.blue),
                              )
                          ),

                        ] , rows:getTableRow()

                    ),


                  )


                ],


              ), onRefresh: onHeaderRefresh),
              Offstage(
                offstage: isloading,
                child: SpinKitFadingCircle(
                  color: Colors.blue,
                  size: 50.0,
                ),
              )
            ],
          )

        ),

        endDrawer: RightEndDrawer(),
      ),
    );
  }

  //通话记录视图
  List<DataRow> getTableRow() {

    List<DataRow> list = [];
    for (int i = 0; i < callRecordData.length; i++) {
      list.add(DataRow(cells: [
        DataCell(Text(
          callRecordData[i].lSH??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].phone??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].typeName??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].seatnum??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].realName??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].comeTime??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].connectTime??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].closeTime??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].connectTypeName??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),
        DataCell(Text(
          callRecordData[i].closeTypeName??"",
          style: TextStyle(fontSize: ScreenUtil().setSp(35)),
        )),

      ]));
    }
    print(list.length);

    return list;

  }

  //刷新
  Future<Null> onHeaderRefresh() async{

    page = 1;
    callRecordData.clear();
    getCallRecordData();

  }

  Future getCallRecordData() async{

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    print("通话记录key===$key");
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "GetMyAndChildrenPhoneHistory",
      "wherestr":wherestr,
      "limit": 20,
      "page": page,
      "sortName": "CreateDate",
      "sortOrder": "desc","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/postrowdataforlayui",
        data: data);

    print("${WebConfig().baseUrl + "DB/postrowdataforlayui"}");
    print("通话记录:${response}==$data");

    if (response.data["code"] == 0) {
      for (int i = 0; i < response.data["data"].length; i++) {
        CallRecordListData callRecordListEntity =
        new CallRecordListData.fromJson(response.data["data"][i]);
        callRecordData.add(callRecordListEntity);
      }
      isloading = true;
      if (mounted) {
        setState(() {});
      }
    } else {
      Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
    }
  }

}
